package com.hmdp.mylock.impl;

import cn.hutool.core.lang.UUID;
import com.hmdp.mylock.ILock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author 24040
 * @name SimpleRedisLock
 * @date 2022-11-11 14:35
 * 简单锁
 */
@Slf4j
public class SimpleRedisLock implements ILock {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String name;//锁的名称
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";//UUID前缀
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;//这里的泛型指定返回值类型

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));//设置脚本位置
        UNLOCK_SCRIPT.setResultType(Long.class);//设置返回值类型
    }

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String name) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取当前线程的id
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁，key为KEY_PREFIX+name，value 值为当前的线程
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name,
                threadId, timeoutSec, TimeUnit.SECONDS);
        // 有个自动拆箱的操作
        return Boolean.TRUE.equals(flag);//避免空指针风险
    }

    /*@Override
    public void unLock() {
        // 获取线程标识，再判断线程标识是否一致
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁中的标识
        String cacheId = redisTemplate.opsForValue().get(KEY_PREFIX + name);
        // 如果当前线程id和锁里面存放的id一致，那么就代表该锁是同一个线程，可以进行删除操作
        if(threadId.equals(cacheId)){
            // 释放锁，完成
            redisTemplate.delete(KEY_PREFIX + name);
        }
    }*/

    @Override
    public void unLock() {
        //调用lua脚本，进行锁的删除操作，删除线锁的时候要去判断一下，线程标识和缓存中存入的线程标识一致
        redisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),//把key转换为list
                ID_PREFIX + Thread.currentThread().getId()
        );
    }
}
